<?php
include 'util/BeanJSONEncoder.php';
include 'util/BeanJSONDecoder.php';

/**
 * @author Andre Albert &lt;andre.albert82@googlemail.com&gt;
 * @since 23.02.2012
 * @package controllers
 */
class QuestionController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
		// dispatch 
		if ($this->getRequest()->isPost()) {
			$request_body = @file_get_contents('php://input');
			$this->doPost($request_body);
		} else if ($this->getRequest()->isDelete()) {
			$this->doDelete();
		} else {
			$this->doGet();
		}
		exit;
    }
    
    public function doDelete() {
    	$log = Zend_Registry::get('log');
    	$questionId = $_GET['id'];
    	
    	$log->log('Removing Question '.$questionId, 1);
    	$ps = new Application_Model_PersistenceService();
    	$ps->removeQuestion($questionId);
    	exit;
    }

    /**
     * Queries all the question and returns them.
     */
    public function listAction() {
    	$ps = new Application_Model_PersistenceService();
    	$question = $ps->getQuestions();
    	$json = Application_util_BeanJSONEncoder::encode($question);
    	echo $json;
    	exit;
    }
    
    
    public function doGet() {
    	$ps = new Application_Model_PersistenceService();
    	$all = $_GET['list'];
    	$nextQuestionId = $_GET['question'];

    	if (isset($all)) {
    		$question = $ps->getQuestions();
    	} else if ($nextQuestionId === null) {
			// calculate next Question Here
    		if (rand(0,3) == 0) 
    			$question = $ps->fetchRandomQuestion($_GET['conversation']);
    		else 
    			$question = $ps->fetchRelevantQuestion($_GET['conversation']);
    		
    	} else {
    		$question = $ps->getQuestion($nextQuestionId);
    	}
    	
    	$json = Application_util_BeanJSONEncoder::encode($question);
		echo $json;
    }
    
    /**
     * Return a single question.
     */
    private function doPost($request_body) {
    	$decodedQuestion = Application_util_BeanJSONDecoder::decode($request_body, Zend_Json::TYPE_OBJECT);
    	
    	$ps = new Application_Model_PersistenceService();
    	$ps->saveQuestion($decodedQuestion);
    	
    	echo Application_util_BeanJSONEncoder::encode($decodedQuestion);
    }
}
